The System.Configuration Namespace

Currently, all of the *.config files shown in this chapter have made use of well-known XML elements that are read by the CLR to resolve the location of external assemblies. In addition to these recognized elements, it is perfectly permissible for a client configuration file to contain application-specific data that has nothing to do with binding heuristics. Given this, it should come as no surprise that the .NET Framework provides a namespace that allows you to programmatically read the data within a client configuration file.

The System.Configuration namespace provides a small set of types you can use to read custom data from a client’s *.config file. These custom settings must be contained within the scope of an <appSettings> element. The <appSettings> element contains any number of <add> elements that define key/value pairs to be obtained programmatically.

For example, assume you have an App.config file for a Console Application named AppConfigReaderApp that defines two application specific values, listed like so:

<configuration>
    <appSettings>
        <add key="TextColor" value="Green" />
        <add key="RepeatCount" value="8" />
    </appSettings>
</configuration>

Reading these values for use by the client application is as simple as calling the instance-level GetValue() method of the System.Configuration.AppSettingsReader type. As shown in the following code, the first parameter to GetValue() is the name of the key in the *.config file, whereas the second parameter is the underlying type of the key (obtained via the C# typeof operator):

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace AppConfigReaderApp
{
    class Program
    {
        static void Main(string[] args)
        {    
            Console.WriteLine("***** Reading <appSettings> Data *****\n");

            // Get our custom data from the *.config file.
            AppSettingsReader ar = new AppSettingsReader();
            int numbOfTimes = (int)ar.GetValue("RepeatCount", typeof(int));
            string textColor = (string)ar.GetValue("TextColor", typeof(string));

            Console.ForegroundColor =
                (ConsoleColor)Enum.Parse(typeof(ConsoleColor), textColor);

            // Now print a message correctly.
            for (int i = 0; i < numbOfTimes; i++)
                Console.WriteLine("Howdy!");
            Console.ReadLine();
        }    
    }
}

As you work throughout the remainder of the book, you will find many other important sections that can be found within a client (or web-based) configuration file. To be sure, the deeper you dive into .NET programming, the more critical an understanding of XML configuration files become.

Source Code The AppConfigReaderApp application can be found under the Chapter 14 subdirectory.